'use strict';
const {
	verifyToken
} = require("wx-common")

exports.main = async (event, context) => {
	//event为客户端上传的参数
	const db = uniCloud.database()
	const dbCmd = db.command
	console.log('article event : ', event)
	const payload = event.token ? verifyToken(event.token) : null
	let dbRes;
	if (event.action == "create") {
		dbRes = await db.collection('article').add({
			owner: payload.openid,
			name: event.name,
			avatarUrl: event.avatarUrl,
			date: event.date,
			html: event.html,
			title: event.title,
			url: event.url,
			type: event.type
		})
	} else if (event.action == "query") {
		if (event.type) {
			dbRes = await db.collection("article").where({
				type: event.type
			}).orderBy('_id', 'desc').get()
		} else {
			dbRes = await db.collection("article").orderBy('_id', 'desc').get()
		}
	} else if (event.action == "search") {
		dbRes = await db.collection("article").where({
			title: new db.RegExp({
				regex: event.key, // 正则表达式为 /^\ds/，转义后变成 '^\\ds'
				options: 'i' // i表示忽略大小写
			})
		}).get()
	}

	//返回数据给客户端
	return dbRes
};
